<template>
	<view v-show="pageShow">
		<form @submit="formSubmit">
			<view class="uni-form-item" style="margin-bottom: 10rpx;">
				<view class="title">指定收货位</view>
				<switch :checked="locationChecked" @change="handleLocationChange" />
			</view>
			<view class="uni-form-item">
				<view class="title">货品代码</view>
				<view class="uni-input-container">
					<view class="uni-input-view">
						<input class="uni-input" v-model="inBillCargo.code" :focus="focus[0]" @input="inBillCargo.id = null;" @confirm="handleConfirmInBillCargo"
						 placeholder="请扫描货品代码" />
						<image src="/static/scan.png" class="scan" @click="handleScanInBillCargo" />
					</view>
					<image src="/static/search.png" class="search" @click="handleConfirmInBillCargo" />
				</view>
			</view>
			<view class="uni-form-item">
				<view class="title">扫描到托盘</view>
				<view class="uni-input-container">
					<view class="uni-input-view">
						<input class="uni-input" v-model="pallet.code" :focus="focus[1]" @input="pallet.id = null;" @confirm="handleConfirmPallet"
						 placeholder="请扫描托盘号" />
						<image src="/static/scan.png" class="scan" @click="handleScanPallet" />
					</view>
					<image src="/static/search.png" class="search" @click="handleConfirmPallet" />
				</view>
			</view>
			<view class="uni-form-item" v-if="locationChecked">
				<view class="title">收货到货位</view>
				<view class="uni-input-container">
					<view class="uni-input-view">
						<input class="uni-input" v-model="goodsLocation.code" :focus="focus[2]" @input="goodsLocation.id = null;" @confirm="handleConfirmGoodsLocation"
						 placeholder="请扫描收货货位" />
						<image src="/static/scan.png" class="scan" @click="handleScanGoodsLocation" />
					</view>
					<image src="/static/search.png" class="search" @click="handleConfirmGoodsLocation" />
				</view>
			</view>
			<view class="uni-form-item">
				<view class="title">收货数量</view>
				<input class="uni-input border" type="number" v-model="receiveAmount" :focus="focus[3]" placeholder="请输入收货数量" />
			</view>
			<view class="list-card" style="margin-top: 50rpx;">
				<uni-card :title="'入库单号：' + bill.billNo" @click="handleDetail">
					<view class="item">
						<view class="item-content">
							<label>状态：</label>
							<text class="status" :class="{warning: bill.inBillState < '400'}">{{bill.inBillStateName || '-'}}</text>
						</view>
						<view class="item-content">
							<label>类型：</label>
							<text>{{bill.inOrderTypeName || '-'}}</text>
						</view>
					</view>
					<view class="item">
						<view class="item-content">
							<label>外部单号：</label>
							<text>{{bill.outOrderNo || '-'}}</text>
						</view>
						<view class="item-content">
							<label>预期收货：</label>
							<text>{{bill.expectedArrivalTime ? $formatter.formatDate(new Date(bill.expectedArrivalTime)) : '-'}}</text>
						</view>
					</view>
					<view class="item-footer">
						<view class="footer-item">
							<label>总预期量</label>
							<text>{{bill.totalExpect ? parseInt(bill.totalExpect) : '-'}}</text>
						</view>
						<view class="footer-item">
							<label>已收数量</label>
							<text>{{bill.totalGoods ? parseInt(bill.totalGoods) : '-'}}</text>
						</view>
					</view>
				</uni-card>
			</view>
			<view class="uni-btn-v">
				<button type="primary" form-type="submit">收货</button>
			</view>
		</form>
		<uni-popup ref="cargoSelect" type="bottom">
			<view class="table">
				<view class="table-head">
					<view class="th">
						<view class="td" style="flex: 1;"></view>
						<view class="td" style="flex: 3;">货品代码</view>
						<view class="td" style="flex: 3;">货品名称</view>
					</view>
				</view>
				<scroll-view style="max-height: 600rpx;" scroll-y="true">
					<view class="table-body">
						<view class="tr" v-for="item in inBillCargo.list" :key="item.id" @click="handleSelectInBillCargo(item)">
							<view class="td" style="flex: 1;">
								<radio :checked="inBillCargo.id === item.id" />
							</view>
							<view class="td" style="flex: 3;">{{item.goodsCode || '-'}}</view>
							<view class="td" style="flex: 3;">{{item.goodsName || '-'}}</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</uni-popup>
		<uni-popup ref="palletSelect" type="bottom">
			<view class="table">
				<view class="table-head">
					<view class="th">
						<view class="td" style="flex: 1;"></view>
						<view class="td" style="flex: 2;">托盘号</view>
						<view class="td" style="flex: 2;">库存数量</view>
						<view class="td" style="flex: 2;">托盘类型</view>
					</view>
				</view>
				<scroll-view style="max-height: 600rpx;" scroll-y="true">
					<view class="table-body">
						<view class="tr" v-for="item in pallet.list" :key="item.id" @click="handleSelectPallet(item)">
							<view class="td" style="flex: 1;">
								<radio :checked="pallet.id === item.id" />
							</view>
							<view class="td" style="flex: 2;">{{item.code || '-'}}</view>
							<view class="td" style="flex: 2;">{{item.quantity || '-'}}</view>
							<view class="td" style="flex: 2;">{{item.palletTypeLabel || '-'}}</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</uni-popup>
		<uni-popup ref="goodsLocationSelect" type="bottom">
			<view class="table">
				<view class="table-head">
					<view class="th">
						<view class="td" style="flex: 1;"></view>
						<view class="td" style="flex: 2;">货位代码</view>
						<view class="td" style="flex: 2;">储区代码</view>
						<view class="td" style="flex: 2;">货位状态</view>
					</view>
				</view>
				<scroll-view style="max-height: 600rpx;" scroll-y="true">
					<view class="table-body">
						<view class="tr" v-for="item in goodsLocation.list" :key="item.id" @click="handleSelectGoodsLocation(item)">
							<view class="td" style="flex: 1;">
								<radio :checked="goodsLocation.id === item.id" />
							</view>
							<view class="td" style="flex: 2;">{{item.code || '-'}}</view>
							<view class="td" style="flex: 2;">{{item.storageAreaCode || '-'}}</view>
							<view class="td" style="flex: 2;">{{item.stateLabel || '-'}}</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import uniCard from '@/components/uni-card/uni-card.vue';

	export default {
		components: {
			uniCard
		},
		data() {
			return {
				pageShow: false,
				billId: null,
				bill: {},
				locationChecked: true,
				focus: [true, false, false, false],
				inBillCargo: {
					code: null,
					id: null,
					origin: [],
					list: []
				},
				pallet: {
					code: null,
					id: null,
					list: []
				},
				goodsLocation: {
					code: null,
					id: null,
					list: []
				},
				receiveAmount: null
			}
		},
		onLoad(e) {
			this.billId = e.id;
			uni.showLoading({
				title: '加载中'
			});
			this.getBillCargoList();
			this.fetch();
		},
		methods: {
			handleLocationChange(e) {
				this.locationChecked = e.detail.value;
				if (!this.locationChecked) {
					this.goodsLocationId = null;
					this.$set(this.focus, 2, false)
				}
			},
			handleScanInBillCargo() {
				this.$scan(res => {
					this.inBillCargo.code = res;
					this.handleConfirmInBillCargo();
				});
			},
			handleConfirmInBillCargo() {
				if (this.inBillCargo.code) {
					this.$api.goods.listScan({
						ownerId: this.bill.ownerId,
						code: this.inBillCargo.code
					}).then(res => {
						const _goodsCodeList = res.data.map(v => v.code.toLowerCase());
						this.inBillCargo.list = this.inBillCargo.origin.filter(v => _goodsCodeList.includes(v.goodsCode.toLowerCase()));
						this.handleConfirmInBillCargoCallback();
					});
				} else {
					this.inBillCargo.list = [...this.inBillCargo.origin];
					this.handleConfirmInBillCargoCallback();
				}
			},
			handleConfirmInBillCargoCallback() {
				if (!this.inBillCargo.list.length) {
					uni.showToast({
						title: '未匹配到待收货货品',
						icon: 'none'
					});
					return;
				}
				if (this.inBillCargo.list.length === 1) {
					const _cargo = this.inBillCargo.list[0];
					this.handleSelectInBillCargo(_cargo);
				} else {
					this.$refs.cargoSelect.open();
				}
			},
			handleSelectInBillCargo(cargo) {
				this.inBillCargo.id = cargo.id;
				this.inBillCargo.code = cargo.goodsCode;
				this.receiveAmount = parseInt(cargo.expectQuantity) - parseInt(cargo.receiveAmount || 0);
				setTimeout(() => {
					this.$refs.cargoSelect.close();
					this.inBillCargo.list = [];
					this.handleFocus(1);
				}, 100);
			},
			handleScanPallet() {
				this.$scan(res => {
					this.pallet.code = res;
					this.handleConfirmPallet();
				});
			},
			handleConfirmPallet() {
				this.$api.common.palletList({
					page: 1,
					limit: 100,
					code: this.pallet.code
				}).then(res => {
					this.pallet.list = res.data;
					if (!this.pallet.list.length) {
						uni.showToast({
							title: '未匹配到托盘',
							icon: 'none'
						});
						return;
					}
					if (this.pallet.list.length === 1) {
						const _pallet = this.pallet.list[0];
						this.handleSelectPallet(_pallet);
					} else {
						this.$refs.palletSelect.open();
					}
				});
			},
			handleSelectPallet(pallet) {
				this.pallet.id = pallet.id;
				this.pallet.code = pallet.code;
				setTimeout(() => {
					this.$refs.palletSelect.close();
					this.pallet.list = [];
					this.handleFocus(2);
				}, 100);
			},
			handleScanGoodsLocation() {
				this.$scan(res => {
					this.goodsLocation.code = res;
					this.handleConfirmGoodsLocation();
				});
			},
			handleConfirmGoodsLocation() {
				this.$api.common.goodsLocationList({
					page: 1,
					limit: 100,
					query: this.goodsLocation.code,
					warehouseId: this.$storage.getWarehouseId()
				}).then(res => {
					this.goodsLocation.list = res.data;
					if (!this.goodsLocation.list.length) {
						uni.showToast({
							title: '未匹配到货位',
							icon: 'none'
						});
						return;
					}
					if (this.goodsLocation.list.length === 1) {
						const _goodsLocation = this.goodsLocation.list[0];
						this.handleSelectGoodsLocation(_goodsLocation);
					} else {
						this.$refs.goodsLocationSelect.open();
					}
				});
			},
			handleSelectGoodsLocation(goodsLocation) {
				this.goodsLocation.id = goodsLocation.id;
				this.goodsLocation.code = goodsLocation.code;
				setTimeout(() => {
					this.$refs.goodsLocationSelect.close();
					this.goodsLocation.list = [];
					this.handleFocus(3);
				}, 100);
			},
			handleFocus(index) {
				this.focus.map((v, i) => this.$set(this.focus, i, false));
				if (!this.locationChecked && index === 2) {
					setTimeout(() => this.$set(this.focus, 3, true), 300);
				} else {
					setTimeout(() => this.$set(this.focus, index, true), 300);
				}
			},
			getBillCargoList() {
				this.$api.receiveCargo.billCargoList({
					page: 1,
					limit: 1000,
					billId: this.billId
				}).then(res => {
					this.inBillCargo.origin = res.data.filter(v => parseInt(v.receiveAmount || 0) < parseInt(v.expectQuantity || 0));
					if (this.inBillCargo.origin.length === 1) {
						const cargo = this.inBillCargo.origin[0];
						this.inBillCargo.id = cargo.id;
						this.inBillCargo.code = cargo.goodsCode;
						this.receiveAmount = parseInt(cargo.expectQuantity) - parseInt(cargo.receiveAmount || 0);
						setTimeout(() => {
							this.handleFocus(1);
						}, 100);
					}
				});
			},
			fetch(callback) {
				this.$api.receiveCargo.detail(this.billId).then(res => {
					this.bill = res
					uni.hideLoading();
					this.pageShow = true;
					callback && callback instanceof Function && callback();
				});
			},
			formSubmit() {
				if (!this.inBillCargo.id) {
					if (this.inBillCargo.code) {
						return uni.showToast({
							title: '请扫描合法的货品代码',
							icon: 'none'
						})
					} else {
						return uni.showToast({
							title: '请扫描货品代码',
							icon: 'none'
						})
					}
				}
				if (this.pallet.code && !this.pallet.id) {
					return uni.showToast({
						title: '请扫描合法的收货托盘',
						icon: 'none'
					})
				}
				if (this.goodsLocation.code && !this.goodsLocation.id) {
					return uni.showToast({
						title: '请扫描合法的收货货位',
						icon: 'none'
					})
				}
				if (!this.receiveAmount) {
					return uni.showToast({
						title: '请输入收货数量',
						icon: 'none'
					})
				}
				uni.showLoading({
					title: '收货中'
				});
				const params = {
					inBillId: this.billId,
					inBillCargoId: this.inBillCargo.id,
					palletId: this.pallet.id,
					goodsLocationId: this.goodsLocation.id,
					receiveAmount: this.receiveAmount,
					receiveTimeStr: this.$formatter.formatDateTime(new Date())
				};
				this.$api.receiveCargo.saveReceiveCargo(params).then(res => {
					global.$refresh = true;
					uni.hideLoading();
					uni.showToast({
						title: '收货成功',
						icon: 'success'
					});
					Object.assign(this.inBillCargo, {
						code: null,
						id: null,
						origin: [],
						list: []
					});
					Object.assign(this.pallet, {
						code: null,
						id: null,
						list: []
					});
					Object.assign(this.goodsLocation, {
						code: null,
						id: null,
						list: []
					});
					this.receiveAmount = null;
					this.getBillCargoList();
					this.fetch(() => {
						if (this.bill.inBillState >= '400') {
							setTimeout(() => {
								uni.showToast({
									title: '收货完成',
									icon: 'none'
								});
								setTimeout(() => {
									uni.navigateBack();
								}, 500);
							}, 1000);
						}
					});
				}, () => uni.hideLoading());
			},
			handleDetail() {
				uni.navigateTo({
					url: '/pages/inWarehouse/receive/detail?bill=' + JSON.stringify(this.bill)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.list-card /deep/ .uni-card {
		margin: 0 0 30rpx 0;
	}

	.list-card /deep/ .uni-card .uni-card__header {
		padding: 10rpx 24rpx;
	}
</style>
